import datetime
from django import forms
from django.utils.text import get_text_list
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from models import CommentModel

class CommentForm(forms.ModelForm):
    content_type  = forms.CharField(widget=forms.HiddenInput)
    object_pk     = forms.CharField(widget=forms.HiddenInput)

    class Meta:
        model = CommentModel
        exclude = ('site','is_public','date_posted')
    
    def __init__(self, target_object, data=None, initial=None):
        self.target_object = target_object
        if initial is None:
            initial = {}
        initial.update(self.generate_data())
        super(CommentForm, self).__init__(data=data, initial=initial)
    
    def get_comment_object(self):
        new = CommentModel(
            content_type = ContentType.objects.get_for_model(self.target_object),
            object_pk    = str(self.target_object._get_pk_val()),
            name         = self.cleaned_data["name"],
            comment      = self.cleaned_data["comment"],
            date_of_birth= self.cleaned_data["date_of_birth"],
            date_posted  = datetime.datetime.now(),
            site_id      = settings.SITE_ID,
            is_public    = True,
        )
        
        return new

    def generate_data(self):
        return {
            'content_type'  : str(self.target_object._meta),
            'object_pk'     : str(self.target_object._get_pk_val()),
        } 
        
    def clean_comment(self):
        comment = self.cleaned_data["comment"]
        if settings.COMMENTS_ALLOW_PROFANITIES == False:
            bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
            if bad_words:
                plural = len(bad_words) > 1
                raise forms.ValidationError((
                    "Watch your mouth! The word %s is not allowed here.",
                    "Watch your mouth! The words %s are not allowed here.", plural) % \
                    get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and'))
        return comment

    def clean_date_of_birth(self):
        num_of_days = datetime.date.today() - self.cleaned_data['date_of_birth']
        if num_of_days.days < 18260:
            raise forms.ValidationError('You need to have gray hair and lots of wisdom before you'
                                         ' can comment on this topic!!! Enter an age greater than 50.')
        return self.cleaned_data['date_of_birth']
